<template>
  <layout v-loading="loading">
    <!-- 顶部搜索栏 -->
    <div class="header">
      <div class="w">
        <search-input />
      </div>
    </div>
    <!-- 商品区域 -->
    <div class="bw">
      <!-- 导航栏 -->
      <div class="w pad-10">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ name: 'index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>活动管理</el-breadcrumb-item>
          <el-breadcrumb-item>活动列表</el-breadcrumb-item>
          <el-breadcrumb-item>活动详情</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 商品信息 -->
      <div class="sku-info w pad-10">
        <el-row>
          <!-- 图片展示区域 -->
          <el-col :span="10">
            <el-card class="sku-images" shadow="never">
              <el-carousel height="400px" indicator-position="outside" :loop="false"
                :initial-index="details.imageInitialIndex">
                <el-carousel-item v-for="(image, idx) in details.images" :key="idx">
                  <el-image fit="fill" :src="image.url" />
                </el-carousel-item>
              </el-carousel>
            </el-card>
          </el-col>
          <!-- 商品详细信息 -->
          <el-col :span="14">
            <div class="sku-detail pad-0-20">
              <div class="sku-summary">
                <strong class="fs-16">
                  {{ details.title }}
                </strong>
                <br />
                <strong class="fs-12">
                  {{ details.subtitle }}
                </strong>
              </div>
              <div class="sku-summary summary-price">
                <div class="clearfix">
                  <div class="fl title">商品价格</div>
                  <div class="fl content">
                    <span class="fs-16 red">{{ details.price }}</span>
                  </div>
                </div>
                <div class="clearfix">
                  <div class="fl title">促销</div>
                  <div class="fl content">
                    <span class="fs-16 red">
                      <el-tooltip content="假的，暂未实现~" placement="right" effect="light">
                        1899.00
                      </el-tooltip>
                    </span>
                  </div>
                </div>
              </div>
              <div class="sku-summary pad-10 clearfix">
                <div class="fl title">重&nbsp;&nbsp;&nbsp;&nbsp;量&nbsp;</div>
                <div class="fl content">
                  <span>
                    <el-tooltip content="假的，暂未实现~" placement="right" effect="light">
                      0.415kg
                    </el-tooltip>
                  </span>
                </div>
              </div>
              <div class="sku-line"></div>
              <div class="sku-summary pad-10">
                <div class="choose-attrs">
                  <div v-for="(attr, idx) in details.saleAttrs" :key="idx" class="choose-attr clearfix">
                    <div class="fl at">{{ attr.name }}</div>
                    <div class="fl ac clearfix">
                      <div v-for="(av, vidx) in attr.values" :key="vidx"
                        :select="(av.skuIds.indexOf(details.id) !== -1)"
                        @click="selectSaleAttrEvent($event, attr, av)"
                        @mouseenter.self="mouseenterSaleAttrEvent($event, attr, av)"
                        @mouseleave.self="mouseleaveSaleAttrEvent($event, attr, av)"
                        :class="'fl item' + (av.skuIds.indexOf(details.id) !== -1 ? ' selector' : '')">
                        <a class="clearfix">
                          <i class="fl">{{ av.value }}</i>
                        </a>
                      </div>
                    </div>
                  </div>
                  <!-- TODO 带图片的销售属性 -->
                  <!-- <div class="choose-attr clearfix">
                    <div class="fl at">选择颜色</div>
                    <div class="fl ac clearfix">
                      <div class="fl item selector">
                        <a class="clearfix">
                          <el-image
                            class="fl"
                            src="https://img12.360buyimg.com/n9/s40x40_jfs/t1/148767/39/18017/86358/5fd32ff0E5ca41721/d885f7c401dfa557.jpg.avif"
                          >
                          </el-image>
                          <i class="fl">黑色</i>
                        </a>
                      </div>
                      <div class="fl item">
                        <a class="clearfix">
                          <el-image
                            class="fl"
                            src="https://img12.360buyimg.com/n9/s40x40_jfs/t1/148767/39/18017/86358/5fd32ff0E5ca41721/d885f7c401dfa557.jpg.avif"
                          >
                          </el-image>
                          <i class="fl">黑色</i>
                        </a>
                      </div>
                    </div>
                  </div> -->
                </div>
              </div>
              <div class="sku-line"></div>
              <div class="sku-summary pad-10">
                <el-form :inline="true">
                  <el-form-item>
                    <!-- TODO 需要设置最大数量，可以通过库存或者设置进行赋值 -->
                    <el-input-number size="large" v-model="count" :min="1" />
                  </el-form-item>
                  <el-form-item>
                    <template v-if="details.inStock">
                      <el-button size="large" type="danger" :disabled="submitted" @click="addCartEvent">加入购物车</el-button>
                    </template>
                    <template v-if="!details.inStock">
                      <el-button size="large" type="danger" plain disabled>到货通知</el-button>
                    </template>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- 商品详情 -->
      <div class="w detail">
        <el-tabs v-model="activeTabName" type="border-card">
          <el-tab-pane name="introduce" label="商品介绍">
            <div class="detail-content">
              <div class="parameter">
                <el-row>
                  <el-col :span="24">
                    <span class="item">
                      品牌：
                      <router-link target="_blank"
                        :to="{ 'name': 'search', 'query': { 'keyword': details.brand.name, 'cate': details.brand.id } }">
                        {{ details.brand.name }}
                      </router-link>
                    </span>
                  </el-col>
                  <!-- TODO 这些信息没有，待补充 -->
                  <!-- <el-col :span="6">
                    <span class="item">商品名称：荣耀play5T 4G</span>
                  </el-col>
                  <el-col :span="6">
                    <span class="item">商品编号：100021830456</span>
                  </el-col>
                  <el-col :span="6">
                    <span class="item">商品毛重：420.00g</span>
                  </el-col>
                  <el-col :span="6">
                    <span class="item">商品产地：中国大陆</span>
                  </el-col>
                  <el-col :span="6">
                    <span class="item">CPU型号：Unisoc T610</span>
                  </el-col>
                  <el-col :span="6">
                    <span class="item">运行内存：8GB</span>
                  </el-col>
                  <el-col :span="6">
                    <span class="item">机身存储：128GB</span>
                  </el-col> -->
                  <el-col class="clearfix" :span="24">
                    <div class="fr item">
                      <el-link :underline="false" @click="activeTabName = 'attr'">
                        更多参数<icon-svg name="double-arrow-right"></icon-svg>
                      </el-link>
                    </div>
                  </el-col>
                </el-row>
              </div>
              <el-divider style="margin: 0;" />
              <div class="content">
                <p>
                  <el-image 
                    v-for="(introduce, idx) in details.introduce" :key="idx" 
                    :src="introduce" :loading="(idx <= 1) ? 'eager' : 'lazy'" />
                </p>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane name="attr" label="规格与包装">
            <div class="detail-content">
              <div class="attr">
                <el-row v-for="(attrGroup, idx) in details.baseAttrGroups" :key="idx">
                  <el-col :span="4">
                    <icon-svg v-if="attrGroup.icon" :name="attrGroup.icon"></icon-svg>
                    {{ attrGroup.name }}
                  </el-col>
                  <el-col :span="20">
                    <el-form label-position="right" size="small" label-width="160px">
                      <el-form-item 
                        v-for="attrId in attrGroup.attrIds" :key="attrId" 
                        :label="details.baseAttrs[attrId] ? details.baseAttrs[attrId].name : ''">
                        {{ details.baseAttrs[attrId] ? details.baseAttrs[attrId].value : '' }}
                      </el-form-item>
                    </el-form>
                  </el-col>
                  <el-divider v-if="(idx < details.baseAttrGroups.length - 1)"></el-divider>
                </el-row>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane name="protection" label="售后保障">
            <div class="detail-content">
              <div class="protection">
                <div class="header">
                  <strong>售后保障</strong>
                </div>
                <div class="content">
                  <dl>
                    <dt>
                      <p>
                        <icon-svg name="bags"></icon-svg>
                        <strong>商城承诺</strong>
                      </p>
                    </dt>
                    <dd>
                      京东平台卖家销售并发货的商品，由平台卖家提供发票和相应的售后服务。请您放心购买！
                      <br />
                      注：因厂家会在没有任何提前通知的情况下更改产品包装、产地或者一些附件，本司不能确保客户收到的货物与商城图片、产地、附件说明完全一致。只能确保为原厂正货！并且保证与当时市场上同样主流新品一致。若本商城没有及时更新，请大家谅解！
                    </dd>
                    <dt><strong>正品行货</strong></dt>
                    <dd>
                      京东商城向您保证所售商品均为正品行货，京东自营商品开具机打发票或电子发票。
                    </dd>
                  </dl>
                </div>
              </div>
            </div>
          </el-tab-pane>
          <!-- TODO 待实现 -->
          <el-tab-pane name="comment" label="商品评价（50万+）" :lazy="true">
            <div class="detail-content">
              <div class="comment">
                <div class="header">
                  <strong>商品评价</strong>
                </div>
                <div class="feedback clearfix">
                  <div class="f-content fl">
                    <strong>好评率</strong>
                    <div class="f-rate">
                      <span>96</span>
                      <span class="f-percent">%</span>
                    </div>
                  </div>
                </div>
                <div class="nav">
                  <ul>
                    <li>全部评价<em>(200+)</em></li>
                    <li>好评<em>(200+)</em></li>
                    <li>中评<em>(200+)</em></li>
                    <li>差评<em>(200+)</em></li>
                  </ul>
                </div>
                <div class="content">
                  <div v-for="item in 10" :key="item" class="comment-item clearfix">
                    <div class="fl user-column">
                      <div class="user-info">
                        <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                      </div>
                      <div class="user-level">
                        <a>PLUS会员</a>
                      </div>
                    </div>
                    <div class="comment-column">
                      <div class="comment-star">
                        <el-rate clearable />
                      </div>
                      <p class="comment-con">
                        性价比很高，很实惠，使用起来感觉很好，非常完美.^?^.家里亲戚介绍买的，品质好，以后还会回购！
                      </p>
                      <div class="comment-message">
                        <div class="order-info">
                          <span>5L*4桶</span>
                          <span></span>
                          <span></span>
                          <span>2022-10-26 08:34</span>
                        </div>
                        <div class="comment-op fr">
                          <router-link to="/">举报</router-link>
                          <el-link>
                            <icon-svg name="operation" />
                          </el-link>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </layout>
</template>

<script lang="ts" setup>
import store from "@/store/index";
import { useRouter } from "vue-router";
import { ref, reactive, onMounted } from "vue";
import http from "@/utils/httpRequest.js";
import { addElementClassName, removeElementClassName } from "@/utils";

import "@/assets/scss/modules/item.scss";
import Layout from "@/views/commons/layout/index.vue";
import SearchInput from "@/views/commons/search-input.vue";

const router = useRouter();

// 数据加载状态
const loading = ref(true);

// 是否正在提交
const submitted = ref(false);

// 商品详情
const details = reactive({
  id: '',
  title: '',
  subtitle: '',
  price: 0,
  inStock: 0,
  brand: {
    id: '',
    name: '',
  },
  introduce: [],
  images: [],
  imageInitialIndex: 0,
  baseAttrs: { },
  baseAttrGroups: [],
  saleAttrs: [],
});

// 商品数量
const count = ref(1);

// 激活的 tab 标签
const activeTabName = ref('introduce');

// 组件挂载完成后执行
onMounted(() => {
  // 参数 skuId 初始化
  details.id = router.currentRoute.value.params.id + '';
  // 加载 sku 详情
  loadSkuDetails();
});

// 加载 sku 详情
const loadSkuDetails = () => {
  loading.value = true;
  http
    .post({
      url: "/search/sku/details",
      params: { id: details.id },
    })
    .then(({ data }) => {
      if (http.success(data, false)) {
        let body = data.body;
        details.title = body.title;
        details.subtitle = body.subtitle;
        details.price = body.price;
        details.inStock = body.inStock;
        details.saleAttrs = body.saleAttrs;
        details.images = body.images;
        let idx = details.images.findIndex(item => item.default);
        if (idx !== -1) {
          details.imageInitialIndex = idx < 0 ? 0 : idx;
        }
        if (body.brand) {
          details.brand.id = body.brand.id;
          details.brand.name = body.brand.name;
        }
        let baseAttrs = body.baseAttrs;
        for (let i = 0; i < baseAttrs.length; i++) {
          let baseAttr = baseAttrs[i];
          details.baseAttrs[baseAttr.id] = baseAttr;
        }
        details.baseAttrGroups = body.baseAttrGroups;
        details.introduce = body.introduce ? body.introduce.split(',') : [];
        loading.value = false;
      }
    });
};

// 销售属性鼠标移上事件
const mouseenterSaleAttrEvent = (event, attr, av) => {
  // 如果已选中则不作任何处理
  let current = event.currentTarget;
  if (decideSaleAttrSelected(current)) {
    return;
  }
  // 查找选中的 skuId，如果未找到商品，则置灰
  let skuId = locateSelectSkuId(attr, av);
  if (!skuId) {
    addElementClassName(current, "disabled");
    return;
  }
  // 追加选中样式
  addElementClassName(current, "selector");
};

// 销售属性鼠标移出事件
const mouseleaveSaleAttrEvent = (event, attr, av) => {
  // 如果已选中则不作任何处理
  let current = event.currentTarget;
  if (decideSaleAttrSelected(current)) {
    return;
  }
  // 移除选中样式
  removeElementClassName(current, "disabled");
  removeElementClassName(current, "selector");
};

// 选中销售属性事件
const selectSaleAttrEvent = (event, attr, av) => {
  // 已选中属性则不触发点击事件
  let current = event.currentTarget;
  if (decideSaleAttrSelected(current)) {
    return;
  }
  // 查找选中的 skuId
  let skuId = locateSelectSkuId(attr, av);
  if (!skuId) {
    return;
  }
  // 如果匹配到商品则跳转新的商品页面
  router.push({ name: "redirect-item", params: { id: skuId }, });
};

// 查找选中的 skuId，返回 undefined 表示找不到
const locateSelectSkuId = (attr, attrValue) => {
  // 获取选中销售属性的 skuId 集合
  let selectSkuIds = attrValue.skuIds;
  // 获取其他选中销售属性的 skuId 集合
  let otherSelectSkuIds = details.saleAttrs
    .filter(sa => sa.id !== attr.id)
    .map(sa => {
      let sv = sa.values.filter(sav => sav.skuIds.indexOf(details.id) !== -1).pop();
      return sv ? sv['skuIds'] : [];
    });
  // 两个 selectSkuIds 、otherSelectSkuIds 集合取交集，筛选出正确的 skuId
  return selectSkuIds
    .filter(skuId => otherSelectSkuIds.filter(item => item.includes(skuId)).length === otherSelectSkuIds.length)
    .pop();
};

// 判断销售属性是否已选中
const decideSaleAttrSelected = (ele) => {
  return ele && ele.hasAttribute('select') && ele.attributes.select.value === 'true';
};

// 添加购物车事件
const addCartEvent = () => {
  submitted.value = true;
  // 如果会员未登录则需进行登录
  if (!store.getters['memberLoginStatus']) {
    router.push({ name: "login" });
    submitted.value = false;
    return;
  }
  // 提交购物车
  http
    .post({
      url: "/cart/add",
      data: { 
        skuId: details.id,
        count: count.value,
      },
    })
    .then(({ data }) => {
      if (http.success(data, false)) {
        router.push({ name: "cart" });
      }
      submitted.value = false;
    });
};
</script>
